<?php
namespace Tongcheng\Controller;
use Think\Controller;
class IndexController extends CommonController {
    public function index(){
        $a = M('wechat')->where(['wid'=>session('wid')])->find();
       // $this->getcategory();
        $this->assign('pian',$a['pian']);
        $this->display();
    }

    /*
        * 测试，获取账号已经设置的所有类目
        *  GET
        *  URL：https://api.weixin.qq.com/cgi-bin/wxopen/getcategory?access_token=TOKEN
       */
    public function getcategory()
    {
        $model = M("Wechat");
        $map['wid'] = session('wid');
        $info = $model->where($map)->find();
        $authorizer_access_token = $this->getAccessToken($info);
        $url = "https://api.weixin.qq.com/cgi-bin/wxopen/getcategory?access_token={$authorizer_access_token}";
        //var_dump($info);
        //var_dump($url);
        $res = $this->ihttp_get($url);
        $td = json_decode($res, true);
        var_dump($td);exit;
    }
    // public function test(){
    //     $json = file_get_contents("https://www.58zltc.com/Public/layui/lay/modules/areas.json");
    //     $td = json_decode($json, 1);

    //     foreach ($td as $key => $value) {
    //         $new['city_code'] = $value['id'];
    //         $new['city_name'] = $value['areaname'];
    //         $new['pid'] = $value['parentid'];

    //         $new1['pid'] = M("City")->add($new);

    //         foreach ($value['child'] as $k => $v) {
    //             $new1['city_code'] = $v['id'];
    //             $new1['city_name'] = $v['areaname'];
    //             $new2['pid'] = M("City")->add($new1);
    //             foreach ($v['child'] as $idx => $item) {
    //                 $new2['city_code'] = $item['id'];
    //                 $new2['city_name'] = $item['areaname'];
    //                 echo M("City")->add($new2)."<br/>";
    //             }
    //         }
    //     }
    //     // dump($td);
    // }
    //骗审
    public function pian(){
        $status = I('status');
        $new['pian']= $status;
        $a= M('wechat')->where(['wid'=>session('wid')])->save($new);
        if($a){
            $this->success("修改成功");
        }else{
            $this->success("网络繁忙，请稍后再试~");
        }
    }


    public function gobal(){
    	$map['wid'] = session('wid');
    	$model = M("Wechat");
    	if(IS_AJAX){
            if(I('post.sheng') == 0){
                $new['city'] = 0;
            }elseif(I('post.shi') == 0){
                $new['city'] = I('post.sheng');
            }elseif(I('post.xian') == 0){
                $new['city'] = I('post.shi');
            }else{
                $new['city'] = I('post.xian');
            }

            if(I("yong") < 0 || I("yong") > 100){
                $this->error('佣金比例必须大于等于0、小于等于100');
            }
            if(I("withdraw_rate") < 0 || I("withdraw_rate") > 100){
                $this->error('提现抽成比例必须大于等于0、小于等于100');
            }
    		$new['app_id'] = I('post.app_id');
    		$new['app_secret'] = I('post.app_secret');
            $new['tongcheng_fee'] = I('post.tongcheng_fee');
//            $new['shop_fee'] = I('post.shop_fee');
            $new['yong'] = I("post.yong");
            $new['withdraw_rate'] = I("post.withdraw_rate");
    		$model->where($map)->save($new);
    		$this->success("修改成功！");
    	}else{
    		$info = $model->where($map)->find();
    		$this->assign('info',$info);

            if($info['city'] == 0){
                $arr = [0,0,0];
            }else{
                $eq['city_code'] = $info['city'];
                $city = M("City")->where($eq)->find();
                if($city['pid'] != 0){
                    $eq1['id'] = $city['pid'];
                    $pcity = M("City")->where($eq1)->find();
                    if($pcity['pid'] != 0){
                        $eq1['id'] = $pcity['pid'];
                        $pcode = M("City")->where($eq1)->getField('city_code');
                        $arr = [$pcode, $pcity['city_code'], $info['city']];
                    }else{
                        $arr = [$pcity['city_code'], $info['city'], 0];
                    }
                }else{
                    $arr = [$info['city'], 0, 0];
                }
            }
            $this->assign('arr',json_encode($arr));
    		$this->display();
    	}
    }

    public function pay(){
    	$map['wid'] = session('wid');
    	$model = M("Wechat");
    	if(IS_AJAX){
    		$new['mch_id'] = I('post.mch_id');
    		$new['partner_key'] = I('post.partner_key');
            $model->where($map)->save($new);
//            if (I('file')) {
//                $uploads_dir = '../../../ThinkPHP/Library/Vendor/Weixinpay/certificate/';
//                $format = substr(I('file'),strrpos(I('file'), '.'));
//                $name = md5(I('file'));
//                $suc = move_uploaded_file(I('file'), $uploads_dir.$name.$format);
//                var_dump($_FILES);
//                $suc ? $this->success("修改成功！") : '';
//            }
            $this->success("修改成功！");
    		// echo $model->getLastSql();
    	}else{
    		$info = $model->where($map)->find();
    		$this->assign('info',$info);
    		$this->display();
    	}
    }
    //获取模板消息页面
    public function template(){
        $map['wid']=session('wid');
        $list = M('form')->where($map)->select();
        //处理cotent内容
        foreach($list as $k=>$v){
            $list[$k]['content'] = explode("}}",$v['content']);
            array_pop($list[$k]['content']);
        }
        if(IS_AJAX){
           getTemplate();
        }
        $this->assign("list",$list);
        $this->display();
    }


    //展示24小时拼团失败退单记录
    public function refundList()
    {
        $wid = session('wid');
        $count = M('refund')
            ->alias('r')
            ->join('tp_order o on o.id = r.orderid')
            ->join('tp_user u on u.openid = o.openid')
            ->where(array('r.wid'=>$wid ))
            ->count();
        $page = new \Think\Page($count, 20);
        $show = $page->show();
        $info = M('refund')
            ->alias('r')
            ->field('r.*,u.nickname')
            ->join('tp_order o on o.id = r.orderid')
            ->join('tp_user u on u.openid = o.openid')
            ->where(array('r.wid'=>$wid ))
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $this->assign('info',$info);
        $this->assign('show',$show);
        $this->assign('count',$count);
        $this->display();
    }

    public function fabu(){
        //生成小程序。判断是否授权，没有则跳转至授权页面
        $shop_id = I("shop_id");
        $eq['shop_id'] = $shop_id;
        $mini = M('wechat')->where($eq)->find();
        if(!$mini){
            $this->redirect(U("Home/Index/index",array('shop_id'=>$shop_id)));

        }
        $map['wid'] = session('wid');
        $model = M("Wechat");
        $info = $model->where($map)->find();

        $authorizer_access_token = $this->getAccessToken($info);

        $res = $this->ihttp_get("https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token={$authorizer_access_token}");
        $td = json_decode($res, true);
        // dump($td);
        if($td['status'] == 2){
            $this->redirect("step3");
        }
        if(isset($td['status']) && $td['status'] === 0){
            $this->ihttp_post("https://api.weixin.qq.com/wxa/release?access_token={$authorizer_access_token}", "{}");
        }

        $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token={$authorizer_access_token}";
        if($_GET['type'] == 'set'){
            $post_data = array(
                "action"=>'set',
                "requestdomain"=>array("https://www.58zltc.com",'https://apis.map.qq.com','https://tls.qcloud.com','https://webim.tim.qq.com','https://720.58zltc.com'),
                "wsrequestdomain"=>array("wss://socket.58zltc.com"),
                "uploaddomain"=>array("https://www.58zltc.com"),
                "downloaddomain"=>array("https://www.58zltc.com"));
        }else{
            $post_data = array("action"=>'get');
        }
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['errcode'] !== 0){
            $this->reAuth();
        }

        //设置业务域名
        $url2="https://api.weixin.qq.com/wxa/setwebviewdomain?access_token={$authorizer_access_token}";
        $post_data2 = array(
            "action"=>'get',
            //'webviewdomain'=>["https://www.58zltc.com",'https://720.58zltc.com']
        );
        $json2 = json_encode($post_data2, JSON_UNESCAPED_UNICODE);
        $res2 = $this->ihttp_post($url2, $json2);
        $td2 = json_decode($res2, true);
        //不是空的则更新
        if(count($td2['webviewdomain'])<2){
            $url3="https://api.weixin.qq.com/wxa/setwebviewdomain?access_token={$authorizer_access_token}";
            $post_data3 = array(
                "action"=>'set',
                'webviewdomain'=>["https://www.58zltc.com",'https://720.58zltc.com']
            );
            $json3 = json_encode($post_data3, JSON_UNESCAPED_UNICODE);
            $res3 = $this->ihttp_post($url3, $json3);
            $td3 = json_decode($res3, true);
        }


        $vo['webviewdomain'] = implode(',', $td2['webviewdomain']?$td2['webviewdomain']:$td3['webviewdomain']);
        $vo['requestdomain'] = implode(',', $td['requestdomain']);
        $vo['wsrequestdomain'] = implode(',', $td['wsrequestdomain']);
        $vo['uploaddomain'] = implode(',', $td['uploaddomain']);
        $vo['downloaddomain'] = implode(',', $td['downloaddomain']);
        $this->assign('vo',$vo);
        $this->assign('shop_id',$shop_id);
        $this->display('step1');
    }

    public function step2(){
        //shop_id 生成小程序用
        $shop_id = I("shop_id");
        $shop = M("shop")->where(['shop_id'=>$shop_id])->find();
        $model = M("Wechat");
        $map['wid'] = session('wid');
        if($shop_id){
            $wid =M('wechat')->where(['shop_id'=>$shop_id])->find();
            $map['wid'] = $wid?$wid['wid']:session('wid');
        }
        $info = $model->where($map)->find();
        if($shop_id){
            switch($shop['type']){
                case " ":
                    $template_id = 185;
                    $user_desc = "通用";
                    break;
                case "":
                    $template_id = 185;
                    $user_desc = "通用";
                    break;
                case "jiaoyu":
                    $template_id =189;
                    $user_desc = "教育";
                    break;
                case "car":
                    $template_id = 188;
                    $user_desc = "汽车";
                    break;
                case "jiancai":
                    $template_id =169;
                    $user_desc = "建材";
                    break;
            }
        }else{
            if($info['shop_id']){
                $info2 =M("shop")->where(['shop_id'=>$info['shop_id']])->find();
                switch($info2['type']){
                    case " ":
                        $template_id = 185;
                        $user_desc = "通用";
                        break;
                    case "":
                        $template_id = 185;
                        $user_desc = "通用";
                        break;
                    case "jiaoyu":
                        $template_id =189;
                        $user_desc = "教育";
                        break;
                    case "car":
                        $template_id = 188;
                        $user_desc = "汽车";
                        break;
                    case "jiancai":
                        $template_id =169;
                        $user_desc = "建材";
                        break;
                }
            }else{
                //$template_id = 136;
                //$template_id = 177;
                //$template_id = 197;
                //$template_id = 286;
                $template_id = 482;
                //只更新庆云同城
                if(session('wid') == 2){
                    $template_id = 482;
                }
                $user_desc ='测试';
            }
        }
        //为授权的小程序帐号上传小程序代码 文档https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1489140610_Uavc4&token=&lang=zh_CN
        $authorizer_access_token = $this->getAccessToken($info);
        $url = "https://api.weixin.qq.com/wxa/commit?access_token={$authorizer_access_token}";

        $ext = array(
            "extEnable" => true,
            'ext'=>array(
                "host" => "https://www.58zltc.com",
                'appid'=>$info['appid'],
            ),
            'window'=>array(
                'navigationBarTitleText'=>$info['nick_name']
            )
        );
        $ext_json = json_encode($ext, JSON_UNESCAPED_UNICODE);

        $post_data = array(
                "template_id"=>$template_id,
                "ext_json"=>$ext_json,
                "user_version"=>'1.03',
                "user_desc"=>$user_desc);

        // if($_SESSION['uid'] == 1 || $_SESSION['uid'] == 2){
        //     $post_data = array(
        //         "template_id"=>66,
        //         "ext_json"=>$ext_json,
        //         "user_version"=>"V0.9.6",
        //         "user_desc"=>"测试版本");
        // }
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);

        if($td['errcode'] !== 0){
            // if($td['errcode'] == 40001 || $td['errcode'] == 50001 || $td['errcode'] == 61007){
            //     $this->reAuth();
            // }
            // $this->error($td['errmsg']);
            $this->reAuth();
        }
        $this->assign('shop_id',$shop_id);
        $this->assign('code_url',U('get_code_img')."?access_token={$authorizer_access_token}");

        $this->display('step2');
    }

    public function step3(){
        $shop_id = I("shop_id");
        if($_GET['type'] == 'set'){
            $map['wid'] = session('wid');
            if($shop_id){
                $wid =M('wechat')->where(['shop_id'=>$shop_id])->find();
                $map['wid'] = $wid?$wid['wid']:session('wid');
            }
            $model = M("Wechat");
            $info = $model->where($map)->find();
            $shop = M("shop")->where(['shop_id'=>$info['shop_id']])->find();
            switch($shop['type']){
                case " ":
                    $pages = "pages/shop/detail";
                    $title = "通用";
                    break;
                case "":
                    $pages = "pages/shop/detail";
                    $title = "通用";
                    break;
                case "jiaoyu":
                    $pages = "pages/jiaoyu/detail";
                    $title = "教育";
                    break;
                case "car":
                    $pages = "pages/car/detail";
                    $title = "汽车";
                    break;
                case "jiancai":
                    $pages = "pages/jiancai/detail";
                    $title = "建材";
                    break;
            }
            //获取授权小程序帐号的可选类目
            $authorizer_access_token = $this->getAccessToken($info);
            $url = "https://api.weixin.qq.com/wxa/get_category?access_token={$authorizer_access_token}";
            $res = $this->ihttp_get($url);
            $td = json_decode($res, true);

            // dump($td);
            if($td['errcode'] !== 0){
                $this->error($td['errmsg']);
            }
            if(count($td['category_list']) == 0){
                $this->error('请登录微信官方小程序后台设置服务类目！');
            }
            $cate = $td['category_list'][0];

            //将第三方提交的代码包提交审核 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1489140610_Uavc4&token=&lang=zh_CN
            $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token={$authorizer_access_token}";

            $post_data = array(
                "item_list"=>array(
                    array(
                        "address"=>$pages?$pages:"pages/index/index",
                        "tag"=>"生活,同城",
                        "first_class"=>$cate['first_class'],
                        "second_class"=>$cate['second_class'],
                        "first_id"=>$cate['first_id'],
                        "second_id"=>$cate['second_id'],
                        "title"=>$title?$title:"首页",
                    )
                )
            );

            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);

            // dump($json);
            // exit();
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['errcode'] !== 0){
                $this->error($td['errmsg']);
            }
            $this->redirect("step3");
        }else{
            $this->display('step3');
        }
    }

    private function reAuth(){
        $appid = C("OPEN_APPID");
        $pre_auth_code = A("Home/Index")->get_pre_auth_code();

        // $pre_auth_code = $pre_auth_code."KG5F";
        $redirect_uri = urlencode("https://www.58zltc.com?type=reset");
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$redirect_uri}";
        $this->error('没有相应的权限，请重新授权！', $url);
    }


    //模块管理
    public function modular()
    {
        if(IS_AJAX){
            $type = I('type');
            //修改排序
            if($type == "sort"){
                $data['sort'] = I('value');
            }
            //修改显示数量
            if($type== 'count'){
                $data['count'] = I('value');
            }
            $eq['id'] = I('id');
            $r = M('tui_cate')->where($eq)->save($data);
            if($r){
                $this->success("修改成功");
            }else{
                $this->success("网络忙，请稍后再试~");
            }
        } else {
            $tui = M("tui_cate")->where(['wid'=>session('wid')])->order('sort desc')->select();
            $this->assign('list',$tui);
            $this->display();
        }

    }
    //删除模块
    public function modulardel(){
        if(IS_AJAX){
            $eq['id'] = I('id');
            $r = M('tui_cate')->where($eq)->delete();
            if($r){
                $this->success("删除成功");
            }else{
                $this->success("网络忙，请稍后再试~");
            }
        }
    }

    //信息流推荐
    public function modular2()
    {
        if(IS_AJAX){
            $data['sort'] = I('order');
            $eq['id'] = I('id');
            M('tui')->where($eq)->save($data);
            $this->success("修改成功");
        } else {
            /*$tuilist = M('tui')->alias("t")->field('t.*')->join("tp_tui_cate tc on tc.id =t.tid")
                ->where(['tc.status'=>1,'t.status'=>1])->order("t.sort desc")->select();*/
            $tuilist = M('tui')->where(['status'=>1])->order("sort desc")->select();
            foreach($tuilist as $kk=>$vv) {
                //用户
                if ($vv['type'] == "member") {
                    $news = M('member')->where(['mid' => $vv['aid']])->find();
                    //是否关注
                    $follow = M('quan_follow')->where(['openid' => I('openid'), 'follow_openid' => $news['openid']])->find();
                    $news['is_follow'] = $follow ? true : false;
                    $news['type'] = 'member';
                    $news['aid'] = $vv['id'];
                    $news['istitle'] = $vv['istitle'];
                    $news['sort'] = $vv['sort'];
                    $news['aname'] = $news['nickname'];
                    if ($news) {
                        $arr = $news;
                    }
                }
                //推荐文章
                if ($vv['type'] == "news") {
                    $news = M('news')->where(['id' => $vv['aid']])->find();

                    $news['pics'] = explode(',', $news['pics']);
                    $count = M('news_reply')
                        ->where(array('nid' => $news['id']))
                        ->group('openid')
                        ->count('id');
                    if (empty($count)) {
                        $count = 0;
                    }
                    $news['reply_num'] = $count;
                    $news['add_time'] = $this->getAnnounceTime($vv['create_time']);
                    $news['type'] = 'news';
                    $news['aid'] = $vv['id'];
                    $news['istitle'] = $vv['istitle'];
                    $news['sort'] = $vv['sort'];
                    $news['aname'] = $news['title'];
                    if ($news) {
                        $arr = $news;
                    }

                }
                //广告
                if ($vv['type'] == 'ad') {
                    $news = M('news')->where(['id' => $vv['aid']])->find();
                    $pics = explode(',', $news['pics']);
                    $news['pics'] = $pics[0];

                    $news['aid'] = $vv['id'];
                    $news['istitle'] = $vv['istitle'];
                    $news['sort'] = $vv['sort'];
                    $news['aname'] = $news['title'];

                    $news['type'] = 'ad';
                    if ($news) {
                        $arr = $news;
                    }
                }
                //商品
                if ($vv['type'] == 'goods') {
                    $news = M('goods')->where(['id' => $vv['aid']])->find();

                    $news['aid'] = $vv['id'];
                    $news['istitle'] = $vv['istitle'];
                    $news['sort'] = $vv['sort'];
                    $news['aname'] = $news['title'];

                    $news['type'] = 'goods';
                    if ($news) {
                        $arr = $news;
                    }
                }
                //话题
                if ($vv['type'] == 'topic') {
                    $ma['topic'] = $vv['content'];
                    $ma['wid'] = session('wid');
                    $news = M('quan')->where($ma)->find();
                    $pics = explode(',', $news['pics']);
                    $news['pics'] = $pics[0];

                    $news['aid'] = $vv['id'];
                    $news['sort'] = $vv['sort'];
                    $news['istitle'] = $vv['istitle'];
                    $news['aname'] = $news['topic'];
                    $news['type'] = 'topic';
                    if ($news) {
                        $arr = $news;
                    }
                    /*$data[$k]['type'] = 'topic';
                    $arr[$v['type']][] =$news;*/
                }
                //商家
                if ($vv['type'] == 'shop') {
                    $m['shop_id'] = $vv['aid'];
                    $news['sort'] = $vv['sort'];
                    $news = M("shop")->where($m)
                        //->where(['join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                        ->order("last_time desc")
                        ->find();
                    //商户距离计算
                    $news['aid'] = $vv['id'];
                    $news['istitle'] = $vv['istitle'];
                    $news['sort'] = $vv['sort'];
                    $news['aname'] = $news['name'];
                    if (I('la') != 'undefined' && I('lo') != 'undefined') {
                        if ($news['latitude'] && $news['longitude']) {
                            $earthRadius = 6367000;
                            $lat1 = (float)I('la');//纬度
                            $lng1 = (float)I('lo');//经度
                            $lat2 = (float)$news['latitude'];
                            $lng2 = (float)$news['longitude'];
                            $lat1 = ($lat1 * pi()) / 180;
                            $lng1 = ($lng1 * pi()) / 180;
                            $lat2 = ($lat2 * pi()) / 180;
                            $lng2 = ($lng2 * pi()) / 180;
                            $calcLongitude = $lng2 - $lng1;
                            $calcLatitude = $lat2 - $lat1;
                            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
                            $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
                            $distance = round($earthRadius * $stepTwo);
                            if ($distance < 1000) {
                                $news['r_distance'] = $distance . '米';
                            } else {
                                $distance = $distance / 1000;
                                $news['r_distance'] = round($distance, 2) . '公里';
                            }
                        } else {
                            $news['r_distance'] = '';
                        }
                    } else {
                        $news['r_distance'] = '';
                    }
                    $news['type'] = 'shop';
                    if ($news) {
                        $arr = $news;
                    }
                }
                //按顺序返回
                $data[$kk] = $arr;
                unset($news);
                unset($arr);
            }
            $this->assign('list',$data);
            $this->display();
        }

    }

    public function addModular()
    {
        if(IS_AJAX){
            //提交表单
            $count = I("count");
            $type = I('type');
            if(!is_numeric($count)){
                $this->success("请输入数字");
            }
            $data['count'] = $count;
            $data['type'] = $type;
            $data['wid'] = session('wid');
            $data['status'] = 1;
            switch($type){
                case "member":
                    $data['title'] = '活跃用户';
                    break;
                case "huodong":
                    $data['title'] = '推荐活动';
                    break;
                case "quan":
                    $data['title'] = '推荐圈子';
                    break;
                case "shop":
                    $data['title'] = '推荐店铺';
                    break;
                case "goods":
                    $data['title'] = '推荐商品';
                    break;
                case "news":
                    $data['title'] = '咨询';
                    break;
                case "topic":
                    $data['title'] = '推荐话题';
                    break;
                case "ad":
                    $data['title'] = '广告';
                    break;
            }
            $r = M('tui_cate')->add($data);
            if($r){
                $this->success("添加成功");
            }else{
                $this->success("网络忙，请稍后再试~");
            }

        }else{
            $this->display();
        }
    }

    protected function getAnnounceTime($time){
        $timestamp = time() - strtotime($time);
        if($timestamp < 3600){
            $str = floor($timestamp/60);
            if($str < 1){
                $str = 1;
            }
            $str .= "分钟前";
        }else if($timestamp >= 3600 && $timestamp <86400){
            $str = floor($timestamp/3600)."小时前";
        }else if($timestamp >= 86400){
            $str = floor($timestamp/86400);
            if($str > 30){
                $str = 30;
            }
            $str .= "天前";
        }
        return $str;
    }
    public function istitle(){
        $model = M("tui");
        $map['id'] = $_POST['id'];
        $arr = $model->where($map)->find();
        $arr['istitle'] ? $save['istitle'] = 0 : $save['istitle'] = 1;
        $row = $model->where($map)->save($save);
        $row ? $this->success("修改成功！") : $this->error("网络忙，请稍后再试！");
    }
    //
    public function editModularStatus () {
        $model = M("tui_cate");
        $map['id'] = $_POST['id'];
        $arr = $model->where($map)->find();
        $arr['status'] ? $save['status'] = 0 : $save['status'] = 1;
        $row = $model->where($map)->save($save);
        $row ? $this->success("修改成功！") : $this->error("网络忙，请稍后再试！");
    }
    public function editModularStatus2 () {
        $model = M("tui");
        $map['id'] = $_POST['id'];
        $arr = $model->where($map)->find();
        $arr['status'] ? $save['status'] = 0 : $save['status'] = 1;
        $row = $model->where($map)->save($save);
        $row ? $this->success("修改成功！") : $this->error("网络忙，请稍后再试！");
    }

    public function get_code_img(){
        $authorizer_access_token = $_GET['access_token'];
        $code_url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$authorizer_access_token}";

        $res = $this->ihttp_get($code_url);

        header("Content-type:image/jpeg;");
        echo $res;
    }



    private function getAccessToken($info){
        if(date("Y-m-d H:i:s") < $info['token_end_time']){
            return $info['authorizer_access_token'];
        }else{
            $token = $this->get_component_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$token}";
            $post_data = array(
                "component_appid"=>C("OPEN_APPID"),
                "authorizer_appid"=>$info['appid'],
                "authorizer_refresh_token"=>$info['authorizer_refresh_token']);
            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['authorizer_access_token']){
                $map['wid'] = $info['wid'];
                $data['authorizer_access_token'] = $td['authorizer_access_token'];
                $data['authorizer_refresh_token'] = $td['authorizer_refresh_token'];
                $data['token_end_time'] = date("Y-m-d H:i:s", time()+$td['expires_in']-60);
                M("Wechat")->where($map)->save($data);
                return $td['authorizer_access_token'];
            }else{
                // dump($td);
                // $this->error($td['errmsg']);
                $this->reAuth();
            }
        }
    }

    private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }

    //拼团24小时不成功自动退款
    public function refundTuanMoney()
    {
        $map['wid'] = session();
    }

    //
    public function paySub () {
        $map['wid'] = session('wid');
        $model = M("Wechat");
        $new['mch_id'] = $_POST['mch_id'];
        $new['partner_key'] = $_POST['partner_key'];

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        //$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        //print_r($info);exit;
        if(!$info) {// 上传错误提示错误信息
            //$this->error($upload->getError());
        } else {// 上传成功
            if ($info['file']) {
                $path = './Uploads/'.$info['file']['savepath']. $info['file']['savename'];
                $new['certificate_path_cert'] = $path;
            }
            if ($info['file_2']) {
                $path_key = './Uploads/'.$info['file_2']['savepath']. $info['file_2']['savename'];
                $new['certificate_path_key'] = $path_key;
            }
        }
        $model->where($map)->save($new);
        $this->success("修改成功！");
    }
    public function cateNav(){
        if(IS_AJAX){
            $model = M("index_cate");
            $map['wid'] = session('wid');
            $res['count'] = $model->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;
            $res['list'] = $model->where($map)->order("add_time desc")->page("{$page},{$limit}")->select();
            foreach($res['list'] as $key=>$value){
                $time = date("Y-m-d H:i:s",$value['add_time']);
                $res['list'][$key]['add_time'] = $time;
                if(empty($value['url'])){
                    $res['list'][$key]['url'] = "无";
                }
            }

            $this->ajaxReturn($res);
        }else{
            $this->display();
        }
    }
    public function cateAdd(){
        if(IS_AJAX){
            $model = M("index_cate");
            $new['wid'] = session('wid');
            $new['name'] = I('post.name');
            $new['status'] = I('post.status');
            $new['url'] = I('post.url');
            $new['add_time'] = time();


            if(empty($new['name'])){
                $this->error('请输入分类名称！');
            }
            if($model->add($new)){
                $this->success('添加成功！');
            }else{
                $this->error('网络忙，请稍后再试！');
            }
        }else{
            $cmap = array();
            $cmap['wid'] = session('wid');
            $cmap['type'] = 'index';
            $list = M("Cate")->where($cmap)->order("sort asc")->field('id,url,title,need_id,type')->select();
            foreach ($list as $k => $v) {
                if($v['need_id']){
                    $list[$k]['url'] = "{$v['url']}?id={$v['id']}";
                }elseif($v['type'] == 'shop'){
                    $list[$k]['url'] = "list?id={$v['id']}";
                }
            }
            $video = array();
            $video['id'] = 0;
            $video['url'] = '/pages/quan/video/list';
            $video['title'] = '短视频';
            array_push($list,$video);
            $this->assign('news_cate',$list);
            $this->display();
        }
    }
    public function cateEdit(){
        $model = M("index_cate");
        $map['id'] = $_GET['id'];

        if(IS_AJAX){
            $new['name'] = I('post.name');
            $new['status'] = I('post.status');
            $new['url'] = I('post.url');
            if(empty($new['name'])){
                $this->error('请输入标题！');
            }
            $model->where($map)->save($new);
            $this->success('修改成功！');
        }else{
            $vo = $model->where($map)->find();

            $cmap = array();
            $cmap['wid'] = session('wid');
            $cmap['type'] = 'index';
            $list = M("Cate")->where($cmap)->order("sort asc")->field('id,url,title,need_id,type')->select();
            foreach ($list as $k => $v) {
                if($v['need_id']){
                    $list[$k]['url'] = "{$v['url']}?id={$v['id']}";
                }elseif($v['type'] == 'shop'){
                    $list[$k]['url'] = "list?id={$v['id']}";
                }
            }
            $video = array();
            $video['id'] = 0;
            $video['url'] = '/pages/quan/video/list';
            $video['title'] = '短视频';
            array_push($list,$video);
            $this->assign('news_cate',$list);

            $this->assign('vo',$vo);
            $this->display('cateAdd');
        }
    }
    public function cateDel(){
        $model = M("index_cate");
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];

        if($model->where($map)->delete()){
            $this->success("删除成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }
    }
    //快速导航
    public function nav()
    {
        $list = M('nav')->where(['wid'=>session('wid')])->select();
        $this->assign('list',$list);
        $this->display();
    }
    //添加
    public function  addNav()
    {
        if(IS_AJAX){
            if(I('id')){
                //添加
                if(!I('imgurl')){
                    $this->error('请上传图片');
                }
                if(!I('title')){
                    $this->error('请填写标题');
                }
                if(!I('position')){
                    $this->error('请选择跳转位置');
                }
                $data['imgurl'] = I('imgurl');
                $data['title'] = I('title');
                $data['status'] = I('status');
                $data['wid'] = session('wid');
                $data['create_time'] = date("Y-m-d H:i:s");
                switch(I('position')){
                    case '2':
                        $data['url'] = '/pages/shop/shop';//好店
                        $data['open_type'] = 'switchTab';
                        $data['position_name'] = '好店';
                        break;
                    case '3':
                        $data['url'] = '/pages/quan/quan';//同城圈
                        $data['open_type'] = 'switchTab';
                        $data['position_name'] = '同城圈';
                        break;
                    case '4':
                        $data['url'] = '/pages/mine/mine';//个人中心
                        $data['open_type'] = 'switchTab';
                        $data['position_name'] = '个人中心';
                        break;
                    case '5':
                        $data['url'] = '/pages/mine/order/order';//订单
                        $data['open_type'] = '';
                        $data['position_name'] = '订单';
                        break;
                    case '6':
                        $data['url'] = '/pages/mine/info/follow';//我的关注
                        $data['open_type'] = '';
                        $data['position_name'] = '我的关注';
                        break;
                    case '7':
                        $data['url'] = '/pages/shop/tccar/index';//同城特惠
                        $data['open_type'] = '';
                        $data['position_name'] = '同城特惠';
                        break;
                    case '8':
                        $data['url'] = '/pages/shop/goods/goods?type=qiang&title=拼团';//拼团
                        $data['open_type'] = '';
                        $data['position_name'] = '拼团';
                        break;
                    case '9':
                        $data['url'] = '/pages/shop/goods/goods?type=qiang&title=砍价';//砍价
                        $data['open_type'] = '';
                        $data['position_name'] = '砍价';
                        break;
                    case '10':
                        $data['url'] = '/pages/shop/goods/goods?type=qiang&title=抢购';//抢购
                        $data['open_type'] = '';
                        $data['position_name'] = '抢购';
                        break;
                }

                $a = M('nav')->where(['id'=>I('id')])->save($data);
            }else{
                //添加
                if(!I('imgurl')){
                    $this->error('请上传图片');
                }
                if(!I('title')){
                    $this->error('请填写标题');
                }
                if(!I('position')){
                    $this->error('请选择跳转位置');
                }
                $data['imgurl'] = I('imgurl');
                $data['title'] = I('title');
                $data['status'] = I('status');
                $data['wid'] = session('wid');
                $data['create_time'] = date("Y-m-d H:i:s");
                switch(I('position')){
                    case '2':
                        $data['url'] = '/pages/shop/shop';//好店
                        $data['open_type'] = 'switchTab';
                        $data['position_name'] = '好店';
                        break;
                    case '3':
                        $data['url'] = '/pages/quan/quan';//同城圈
                        $data['open_type'] = 'switchTab';
                        $data['position_name'] = '同城圈';
                        break;
                    case '4':
                        $data['url'] = '/pages/mine/mine';//个人中心
                        $data['open_type'] = 'switchTab';
                        $data['position_name'] = '个人中心';
                        break;
                    case '5':
                        $data['url'] = '/pages/mine/order/order';//订单
                        $data['open_type'] = '';
                        $data['position_name'] = '订单';
                        break;
                    case '6':
                        $data['url'] = '/pages/mine/info/follow';//我的关注
                        $data['open_type'] = '';
                        $data['position_name'] = '我的关注';
                        break;
                    case '7':
                        $data['url'] = '/pages/shop/tccar/index';//同城特惠
                        $data['open_type'] = '';
                        $data['position_name'] = '同城特惠';
                        break;
                    case '8':
                        $data['url'] = '/pages/shop/goods/goods?type=qiang&title=拼团';//拼团
                        $data['open_type'] = '';
                        $data['position_name'] = '拼团';
                        break;
                    case '9':
                        $data['url'] = '/pages/shop/goods/goods?type=qiang&title=砍价';//砍价
                        $data['open_type'] = '';
                        $data['position_name'] = '砍价';
                        break;
                    case '10':
                        $data['url'] = '/pages/shop/goods/goods?type=qiang&title=抢购';//抢购
                        $data['open_type'] = '';
                        $data['position_name'] = '抢购';
                        break;
                }

                $a = M('nav')->add($data);
            }
            if($a){
                $this->success("操作成功");
            }else{
                $this->success("网络忙，请稍后再试");
            }
        }else{
            $this->display();
        }

    }
    public function up_status(){
        $status = I('status');
        $status = $status == 0?1:0;
        $a = M('nav')->where(['id'=>I('id')])->setField(['status'=>$status]);
        if($a){
            $this->success("操作成功");
        }else{
            $this->success("网络忙，请稍后再试");
        }
    }
    public function delNav()
    {
        if(M('nav')->where(['id'=>I('id')])->delete()){
            $this->success("操作成功");
        }else{
            $this->success("网络忙，请稍后再试");
        }
    }
    //编辑
    public function  editNav()
    {
        if(IS_AJAX){

        }else{
            $list = M('nav')->where(['id'=>I('id')])->find();
            $this->assign('vo',$list);
            $this->display('addNav');
        }

    }
    //佣金比例管理
    public function commission () {
        $arr = M('commission_proportion')->where(['wid' => session('wid')])->find();
        $this->assign('arr', $arr);
        $this->display();
    }
    //保存佣金数据
    public function saveCommission () {
        $post = $_POST;
        $post['wid'] = session('wid');
        $arr = M('commission_proportion')->where(['wid' => session('wid')])->find();
        if ($arr) {
            $suc = M('commission_proportion')->where(['wid' => session('wid')])->save($post);
        } else {
            $post['create_time'] = date('Y-m-d H:i:s', time());
            $suc = M('commission_proportion')->add($post);
        }
        $this->ajaxReturn($suc ? 1 : 0);
    }
}